package cn.monkey.data.entity.datascope;

import cn.monkey.data.entity.dto.ExtensionQueryRequest;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.function.Predicate;

public class IterableDatascopeDefinitionPredicateFactory implements DatascopeDefinitionPredicateFactory {

    private final DatascopeDefinitionPredicateFactory predicateFactory;

    public IterableDatascopeDefinitionPredicateFactory(DatascopeDefinitionPredicateFactory predicateFactory) {
        this.predicateFactory = predicateFactory;
    }
    @Override
    public Predicate<ExtensionQueryRequest> apply(DatascopeDefinition datascopeDefinition) {
        Collection<DatascopeDefinition> or = datascopeDefinition.getOr();
        Predicate<ExtensionQueryRequest> p = extensionQueryRequest -> true;
        if (!CollectionUtils.isEmpty(or)) {
            Predicate<ExtensionQueryRequest> extensionQueryRequestPredicate = or.stream().map(this.predicateFactory)
                    .reduce(Predicate::and)
                    .orElse(extensionQueryRequest -> true);
            p = p.or(extensionQueryRequestPredicate);
        }
        Collection<DatascopeDefinition> and = datascopeDefinition.getAnd();
        if (!CollectionUtils.isEmpty(and)) {
            Predicate<ExtensionQueryRequest> extensionQueryRequestPredicate = and.stream().map(this.predicateFactory)
                    .reduce(Predicate::and)
                    .orElse(extensionQueryRequest -> true);
            p = p.and(extensionQueryRequestPredicate);
        }
        return p;
    }
}
